<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            $value = 'https://vxtool.dingliangames.com/assets/img/avatar.png';
            switch ($data['gender']) {
                case 1:
                    $value = 'https://vxtool.dingliangames.com/assets/img/nan.png';
                    break;
                case 2:
                    $value = 'https://vxtool.dingliangames.com/assets/img/nv.png';
                    break;
            }
//            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param int $type 类型  0金币充值  1  陪玩下单 2 陪玩上车 3 下单结算  4 上车结算 5用户取消订单  6 主播提现  7 管理员变更金额
     * @param string $memo 备注 0时 为充值订单id  type=1时 下单订单id type =2  上车订单id 3 小单订单order_place_pro_id 4 上车id 5 下单id  6 提现id 7 空
     */
    public static function money($money, $user_id, $type, $memo,$num = null)
    {

        if ($type == 1) {
            $content = '下单';
        } elseif ($type == 2) {
            $content = '上车';
        } elseif ($type == 3) {
            $content = '下单结算';
        } elseif ($type == 4) {
            $content = '上车结算';
        } elseif ($type == 5) {
            $content = '取消订单';
        } elseif ($type == 0) {
            $content = '金币充值';
        }
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo, 'type' => $type, 'content' => $content,'num'=>$num]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员守护值
     * @param int $score 守护值
     * @param int $user_id 会员ID
     * @param int $type 类型    1  陪玩结算 2  上车结算   3 管理员变更守护值
     * @param string $memo 备注   type=1时 下单订单order_place_pro_id type =2  上车订单id  3 空
     */
    public static function score($score, $user_id, $type, $memo, $anchor_id, $data = null)
    {
        if ($type == 1) {
            $content = '下单结算';
        } elseif ($type == 2) {
            $content = '上车结算';
        }
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user ) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                if ($type == 2) {
//                    //写入日志
                    ScoreLog::create([
                        'user_id' => $user_id,
                        'score' => $score, 'before' => $before,
                        'after' => $after,
                        'memo' => $memo,
                        'type' => $type,
                        'content' => $content,
//                        'custom_start' => $data['custom_start'],
                        'custom_ing' => $data['custom_ing'],
                        'num_ing' => $data['num_ing'],
                        'num_remain' => $data['num_remain'],
                        'total_num' => $data['total_num'],
                    ]);

                } else {
                    //写入日志
                    ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo, 'type' => $type, 'content' => $content]);
                }

                //守护值累积更新
                $top = Db::name('top')->where('user_id', $user_id)->where('anchor_id', $anchor_id)->find();
                if (empty($top)) {
                    $data = [
                        'user_id' => $user_id,
                        'anchor_id' => $anchor_id,
                        'acc_score' => $score,
                        'createtime' => time(),
                        'updatetime' => time(),
                    ];
                    Db::name('top')->insert($data);
                } else {
                    Db::name('top')->where('user_id', $user_id)->where('anchor_id', $anchor_id)->update([
                        'acc_score' => $top['acc_score'] + $score,
                        'updatetime' => time(),
                    ]);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }
}
